package org.zjvis.datascience.web.controller;

import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.util.ObjectUtil;
import cn.weiguangfu.swagger2.plus.annotation.ApiPlus;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.validation.Valid;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zjvis.datascience.common.constant.UserConstant;
import org.zjvis.datascience.common.dto.user.UserDTO;
import org.zjvis.datascience.common.exception.BaseErrorCode;
import org.zjvis.datascience.common.exception.DataScienceException;
import org.zjvis.datascience.common.model.ApiResult;
import org.zjvis.datascience.common.model.ApiResultCode;
import org.zjvis.datascience.common.util.DozerUtil;
import org.zjvis.datascience.common.util.JwtUtil;
import org.zjvis.datascience.common.vo.user.CreateUserVO;
import org.zjvis.datascience.common.vo.user.PhoneBindVO;
import org.zjvis.datascience.common.vo.user.UserModifyPasswordVO;
import org.zjvis.datascience.service.SmsService;
import org.zjvis.datascience.service.UserService;

/**
 * @description 用户注册短信验证接口 Controller
 * @date 2021-12-13
 */
@ApiPlus(value = true)
@RestController
@RequestMapping("/sms")
@Api(tags = "sms", description = "短信接口")
@Validated
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    /**
     * 用户注册短信验证接口
     */
    @PostMapping("/registerSendMsg")
    public ApiResult<Boolean> sendPhoneCodeAuth(@Valid @RequestBody CreateUserVO userVo) {
        UserDTO user = DozerUtil.mapper(userVo, UserDTO.class);
        String phone = user.getPhone();
        if(userService.checkUserIsExist(phone) || userService.checkUserIsExist(user.getName())){
            throw new DataScienceException(BaseErrorCode.USER_ALREADY_EXIST);
        }
        if(userVo.getCaptchaCode() != null && smsService.checkCaptcha(phone, userVo.getCaptchaCode())) {
            return ApiResult.valueOf(smsService.smsSendMsg(phone, UserConstant.TYPE_OF_REGISTER));
        } else {
            smsService.msgAuth(phone, UserConstant.TYPE_OF_REGISTER);
        }
        return ApiResult.valueOf(smsService.smsSendMsg(phone, UserConstant.TYPE_OF_REGISTER));
    }

    /**
     * 登录短信验证接口，暂时无需短信登录
     */
//    @PostMapping("/loginSendMsg")
//    public ApiResult<Boolean> sendPhoneCodeAuth(@Valid @RequestBody UserPhoneLoginVO userVo) {
//        String phone = userVo.getPhone();
//        if(!userService.checkUserIsExist(phone)) {
//            throw new DataScienceException(BaseErrorCode.USER_INFO_IS_NULL);
//        }
//        if(userVo.getCaptchaCode() != null && smsService.checkCaptcha(phone, userVo.getCaptchaCode())) {
//            return ApiResult.valueOf(smsService.smsSendMsg(phone, UserConstant.TYPE_OF_LOGIN));
//        } else {
//            smsService.msgAuth(phone, UserConstant.TYPE_OF_LOGIN);
//        }
//        return ApiResult.valueOf(smsService.smsSendMsg(phone, UserConstant.TYPE_OF_LOGIN));
//    }


    /**
     * 修改密码时发送短信逻辑
     */
    @PostMapping("/modifySendMsg")
    public ApiResult<Boolean> sendPhoneCodeAuth(@Valid @RequestBody UserModifyPasswordVO userVo) {
        String phone = userVo.getPhone();
        UserDTO userDto = JwtUtil.getCurrentUserDTO();
        if(!userService.checkUserIsExist(phone)) {
            throw new DataScienceException(BaseErrorCode.USER_IS_NOT_EXISTS);
        }
        if(ObjectUtil.isNotNull(userDto) && userDto.getPhone() != null && !userDto.getPhone().equals(phone)) {
            throw new DataScienceException(BaseErrorCode.USER_PHONE_NOT_CORRESPOND);
        }
        if(ObjectUtil.isNull(userDto)) {
            userService.judgeNamePhone(userVo.getName(), phone);
        }
        if(userVo.getCaptchaCode() != null && smsService.checkCaptcha(phone, userVo.getCaptchaCode())) {
            return ApiResult.valueOf(smsService.smsSendMsg(phone, UserConstant.TYPE_OF_MODIFY));
        } else {
            smsService.msgAuth(phone, UserConstant.TYPE_OF_MODIFY);
        }
        return ApiResult.valueOf(smsService.smsSendMsg(phone, UserConstant.TYPE_OF_MODIFY));
    }

    /**
     * 检验输入验证码是否正确
     */
    @PostMapping("/verify")
    public ApiResult<Boolean> phoneCodeVerify(@Valid @RequestBody String phone, @Param(value = "code") String code) {
        smsService.verifyMsgCode(phone, code, UserConstant.TYPE_OF_MODIFY);
        return ApiResult.valueOf(ApiResultCode.SUCCESS);
    }

    /**
     * 发送图片验证码
     */
    @PostMapping(value = "/captcha")
    @ApiOperation(value = "获取图片验证码", notes = "新增用户注册/修改密码验证")
    public ApiResult<String> getCaptchaCode(@RequestBody String phone) {
        ShearCaptcha shearCaptcha = smsService.createCaptcha(phone);
        return ApiResult.valueOf(ApiResultCode.SUCCESS, shearCaptcha.getImageBase64());
    }

    /**
     * 用户绑定手机号，有两个功能 1.账号未绑定手机号，则直接调用此接口给新手机号下发；
     * 2.账号已有手机号，验证旧手机号以后，给新手机号下发
     */
    @PostMapping(value = "/phoneBind")
    @ApiOperation(value = "新手机号绑定时下发短信", notes = "新手机号绑定时下发短信")
    public ApiResult<Object> phoneBind(@Valid @RequestBody PhoneBindVO userVo) {
        if(userService.checkUserIsExist(userVo.getPhone())) {
            throw new DataScienceException(BaseErrorCode.USER_PHONE_ALREADY_BIND);
        }
        if(userVo.getCaptchaCode() != null && smsService.checkCaptcha(userVo.getPhone(), userVo.getCaptchaCode())) {
            return ApiResult.valueOf(smsService.smsSendMsg(userVo.getPhone(), UserConstant.TYPE_OF_BIND));
        } else {
            smsService.msgAuth(userVo.getPhone(), UserConstant.TYPE_OF_BIND);
        }
        return ApiResult.valueOf(smsService.smsSendMsg(userVo.getPhone(), UserConstant.TYPE_OF_BIND));
    }

    /**
     * 用户改绑发送短信验证（用户账号有绑定手机号时）
     */
    @PostMapping(value = "/phoneBindChange")
    @ApiOperation(value = "手机号改绑时下发短信", notes = "手机号改绑时下发短信")
    public ApiResult<Object> changePhoneBind(@RequestBody JSONObject obj) {
        UserDTO user = JwtUtil.getCurrentUserDTO();
        String captchaCode = obj.getString("captchaCode");
        if(captchaCode == null) {
            throw new DataScienceException(BaseErrorCode.USER_CAPTCHA_CODE_ERROR);
        }
        if(!captchaCode.equals("") && smsService.checkCaptcha(user.getPhone(), captchaCode)) {
            return ApiResult.valueOf(smsService.smsSendMsg(user.getPhone(), UserConstant.TYPE_OF_BIND));
        } else {
            smsService.msgAuth(user.getPhone(), UserConstant.TYPE_OF_BIND);
        }
        return ApiResult.valueOf(smsService.smsSendMsg(user.getPhone(), UserConstant.TYPE_OF_BIND));
    }

}
